<template>
    <el-container>
      <el-header class="inside-header">
        <div>
          <!-- 面包屑 -->
          <el-breadcrumb separator=">">
            <el-breadcrumb-item>视频管理</el-breadcrumb-item>
            <el-breadcrumb-item class="breadcrumbColor">摄像头配置</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
      </el-header>
      <el-main>
       <div class="inside-main-box">
          <el-row class="inside-main" style="">
             <el-col :span="6" style="margin-left: 20px;">
               <el-form-item label="道闸编号" size="small">
                  <el-input v-model="formData.monitorName" size="small" maxLength="16" clearable/>
               </el-form-item>
             </el-col>
             <el-col :span="10" style="margin-left: 20px;">
                  <el-button class="sele-but" icon="search" @click="getAll(formData.monitorName)" size="small">查询</el-button>
                  <el-button class="empty-but" icon="refresh" @click="formData.monitorName='';getAll()" size="small">重置</el-button>
                   <el-button class="add-but" @click="addDialog = true" icon="plus" size="small">新增</el-button>
             </el-col>
          </el-row>
       </div>
       <div style="height: 10px; display: flex; align-items: center;background:#f2f4f5;margin:0 -19.5px 0 -20px"></div>
        <div>
          <el-table :data="tableData.rows" height="480" style="width: 100%;">
            <el-table-column align="center" type="index" label="序号" width="80px"/>
            <el-table-column align="center" prop="factory_name" label="所在工厂"  show-overflow-tooltip>
              <template #default="item">
                <span v-if="item.row.factory_id">{{tableData.factoryNames[item.row.factory_id]?.factory_name}}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="cameraIp" label="IP"  show-overflow-tooltip />
            <el-table-column align="center" prop="port" label="端口号"  show-overflow-tooltip />
            <el-table-column align="center" prop="monitorName" label="道闸编号"  show-overflow-tooltip />
            <el-table-column align="center" prop="cameraName" label="出入类型"  show-overflow-tooltip />
<!--            <el-table-column align="center" prop="deviceName" label="设备名称" show-overflow-tooltip />-->
<!--            <el-table-column align="center" prop="deviceType" label="设备型号" show-overflow-tooltip />-->
<!--            <el-table-column align="center" prop="状态" label="状态" show-overflow-tooltip >-->
<!--              <template #default="scope">-->
<!--                <span v-if="scope.row.status===2" style="color:green">已布防</span>-->
<!--                <span v-else-if="scope.row.status===1" style="color:green">已连接</span>-->
<!--                <span v-else-if="scope.row.status===0" style="color:red">已停用</span>-->
<!--                <span v-else-if="scope.row.status===-1" style="color:#b9b4b4">未检测到</span>-->
<!--                <span v-else style="color:#b9b4b4">未知</span>-->
<!--              </template>-->
<!--            </el-table-column>-->
            <el-table-column align="center" label="操作" fixed="right" width="240">
              <template #default="scope">
<!--                <el-button link type="primary" size="small" icon="view" @click="test(scope.row)">测试</el-button>-->
<!--                <el-button link type="primary" size="small" :disabled="scope.row.status!=1" icon="sunset"
                           @click="getAlertStream(scope.row)">布控</el-button>-->
                <el-button link type="primary" size="small" icon="edit" @click="showDetail(scope.row)">修改</el-button>
                <el-button link type="danger"  size="small" icon="delete" @click="del(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-main>
      <!--新增弹窗-->
      <el-dialog v-model="addDialog" title="摄像头配置" width="40%">
          <div style="width: 90%">
              <el-form  ref="ruleFormRef" :model="formData.form" status-icon :rules="rules" label-width="100px">
                  <el-form-item label="所在工厂" v-if="factoryId>0">
                    <el-input v-model="factory_name" disabled style="width:220px"></el-input>
                  </el-form-item>
                  <el-form-item label="所在工厂" prop="factory_id" v-else>
                    <el-select  clearable v-model="formData.form.factory_id" placeholder="请输入" autocomplete="off" >
                      <el-option v-for="(fac,index) in tableData.factorys" :label="fac.factory_name" :value="fac.id" :key="index">
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="IP" prop="cameraIp">
                    <div>
                      <el-input  clearable v-model="formData.form.cameraIp" placeholder="请输入" maxLength="15" style="width:220px" autocomplete="off" />
                    </div>
                    <div>
                      <span style="font-size: 12px;color: #888;margin-left:15px">认真填写,错误将导致无法连接</span>
                    </div>
                  </el-form-item>
                  <el-form-item label="端口号" prop="port">
                    <div>
                      <el-input  clearable v-model="formData.form.port" placeholder="请输入" maxLength="16" style="width:220px" autocomplete="off" />
                    </div>
                    <div>
                      <span style="font-size: 12px;color: #888;margin-left:15px"> 认真填写,错误将导致无法连接</span>
                    </div>
                  </el-form-item>
                  <el-form-item label="道闸编号" prop="monitorName">
                    <div>
                      <el-input  clearable v-model="formData.form.monitorName" maxLength="16" placeholder="请输入" style="width:220px" autocomplete="off" />
                    </div>
                    <div>
                      <span style="font-size: 12px;color: #888;margin-left:15px">汉字,字母或数字,同工厂不可重复</span>
                    </div>
                  </el-form-item>
                  <el-form-item label="出入类型" prop="cameraName">
                    <div>
                      <el-select clearable  v-model="formData.form.cameraName" placeholder="请选择">
                        <el-option value="入厂" label="入厂" key="1"></el-option>
                        <el-option value="出厂" label="出厂" key="2"></el-option>
                      </el-select>
                    </div>
                    <div>
                      <span style="font-size: 12px;color: #888;margin-left:15px">根据摄像头拍摄位置设置</span>
                    </div>
                  </el-form-item>
<!--                  <el-form-item label="设备名称" prop="deviceName">-->
<!--                      <el-input  disabled v-model="formData.form.deviceName" placeholder="检测后自动填充" style="width:220px" autocomplete="off" />-->
<!--                  </el-form-item>-->
<!--                  <el-form-item label="设备型号" prop="deviceType">-->
<!--                      <el-input  disabled v-model="formData.form.deviceType" placeholder="检测后自动填充" style="width:220px" autocomplete="off" />-->
<!--                  </el-form-item>-->
              </el-form>
          </div>

          <template #footer>
              <span class="dialog-footer">
                <el-button class="sele-but" @click="save(formData.form)"> 确定 </el-button>
                <el-button class="empty-but" @click="close()">取消</el-button>
              </span>
          </template>
      </el-dialog>
      <!--新增弹窗-->
      <el-dialog v-model="showInfo" title="抓拍机信息" width="40%">
          <el-form  ref="ruleFormRef" :model="formData.info" size="mini" label-width="100px" style="margin-left:15%;padding:0">
            <el-form-item label="状态" prop="status">
              <span v-if="formData.info.status===1" style="color:green">正常</span>
              <span v-else-if="formData.info.status===0" style="color:red">停用</span>
              <span v-else style="color:#b9b4b4">故障</span>
            </el-form-item>
            <el-form-item label="deviceID" prop="deviceID">
              <span>{{formData.info.deviceID}}</span>
            </el-form-item>
            <el-form-item label="deviceName" prop="deviceName">
              <span>{{formData.info.deviceName}}</span>
            </el-form-item>
            <el-form-item label="deviceType" prop="deviceType">
              <span>{{formData.info.deviceType}}</span>
            </el-form-item>
            <el-form-item label="macAddress" prop="macAddress">
              <span>{{formData.info.macAddress}}</span>
            </el-form-item>
            <el-form-item label="serialNumber" prop="serialNumber">
              <span>{{formData.info.serialNumber}}</span>
            </el-form-item>
            <el-form-item label="deviceDescription" prop="deviceDescription">
              <span>{{formData.info.deviceDescription}}</span>
            </el-form-item>
            <el-form-item label="encoderVersion" prop="encoderVersion">
              <span>{{formData.info.encoderVersion}}</span>
            </el-form-item>
            <el-form-item label="firmwareVersion" prop="firmwareVersion">
              <span>{{formData.info.firmwareVersion}}</span>
            </el-form-item>
            <el-form-item label="hardwareVersion" prop="hardwareVersion">
              <span>{{formData.info.hardwareVersion}}</span>
            </el-form-item>
            <el-form-item>
              <el-button style="margin-left:70%" @click="showInfo=false">关闭</el-button>
            </el-form-item>
          </el-form>
      </el-dialog>
    </el-container>
</template>

<script setup>
import { onMounted,onBeforeUnmount, reactive, ref, } from "vue";
import {getCameraInfo,addCameraInfo,modifyCameraInfo,delCameraInfo,getDeviceInfo} from "@/api/video"
import {getFactoryInfo} from "@/api/factory"
import {ElMessage, ElLoading, ElMessageBox} from "element-plus";
const tableData = reactive({
  rows: [],
  total: 0,
  factorys:[],
  factoryNames:{}
});
const factoryId = localStorage.getItem("factoryId");
const factory_name = localStorage.getItem("factory_name");
const formData = reactive({
  monitorName:'',
  form:{
    factory_id:null,
    cameraIp:"",
    port:"",
    monitorName:"",
    cameraName:"",
    deviceName:"",
    deviceType:"",
    status:null,
  },
  info:{
    deviceID:"",
    deviceLocation: "",
    deviceName:"",
    deviceType:"",
    macAddress:"",
    model: "",
    serialNumber: "",
  }
})
const addDialog = ref(false)
const showInfo = ref(false)
const close = () => {
  formData.form={
    factory_id:null,
    cameraIp:"",
    port:"",
    monitorName:"",
    cameraName:"",
    deviceName:"",
    deviceType:"",
    status:null,
  }
  addDialog.value = false;
};
const rules = {
  cameraIp: [{required: true, message: "请输入ip地址", trigger: "blur", }],
  port: [{required: true, message: "请输入端口号", trigger: "blur", }],
  monitorName:[{required:true,message: "请输入道闸编号",trigger:"blur"}],
  cameraName:[{required:true,message: "请输入出入类型",trigger:"blur"}],
  factory_id:[{required:true,message: "选择工厂",trigger:"blur"}],
};
const getAll = (name) =>{
  getCameraInfo({monitorName:name}).then(res=>{
    tableData.rows = res.data;
  })
}

const getFactorys = () =>{
  getFactoryInfo({pageSize:1000}).then(res=>{
    let factorys = [];
    res.data?.list.forEach(e=>{
      factorys.push(e);
      tableData.factoryNames[e.id]=e;
    })
    tableData.factorys = factorys;
  })
}

const loading = ref(null);
const test = (row) =>{
  loading.value = ElLoading.service({
    lock:true,
    text:"检测中",
    background:'rgba(0,0,0,0.1)'
  })
  getDeviceInfo(row).then(res=>{
    if(res.code==200){
      formData.info = res.data;
      formData.info.status = 1;
      row.status =1;
      row.deviceName = formData.info.deviceName;
      row.deviceType = formData.info.deviceType;
      showInfo.value=true;
    }else{
      row.status =-1;
      ElMessage.error(res.msg);
    }
    loading.value.close();
  }).catch(()=>{
    row.status =-1;
    ElMessage.error("没有检测到设备,请查证.");
    loading.value.close();
  });
}

let websocket;
const getAlertStream= (row) =>{
  let url = "ws://192.168.1.100:9099/mywebsocket";
  if(!websocket){
    websocket = new WebSocket(url);
  }else if(websocket.readyState!==1){
    // websocket.close();
  }
  //连接发生错误的回调方法
  websocket.onerror = onerror
  //连接成功建立的回调方法
  websocket.onopen = onopen
  //接收到消息的回调方法
  websocket.onmessage = onmessage
  //连接关闭的回调方法
  websocket.onclose = onclose;
  //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
  window.onbeforeunload = function () {
    console.log("before");
  }
  setTimeout(function(){
    if(websocket.readyState===1){
      websocket.send(JSON.stringify(row));
    }
  },500)
}

const onopen = ()=>{

}
const onmessage = (evt)=>{
  if(evt.data.indexOf("licensePlate")>0){
    console.log("message=",evt.data);
    let element = JSON.parse(evt.data);
    console.log("element=",element)
  }else{
    console.log("data=",evt.data)
  }
}
const onerror = ()=>{

}
const onclose = ()=>{

}

const showDetail = (row) =>{
  formData.form = JSON.parse(JSON.stringify(row));
  addDialog.value = true;
}
let ruleFormRef = ref(null);
const save = (row) =>{
  ruleFormRef.value.validate(valid=>{
    if(valid){
      let params = JSON.parse(JSON.stringify(row));
      if(params.id){
        modifyCameraInfo(params).then(res=>{
          if(res&&res.code==200){
            revert();
          }else{
            ElMessage.error(res&&res.msg||"重复的ip或道闸编号");
            revert();
          }
        })
      }else{
        addCameraInfo(params).then(res=>{
          if(res&&res.code==200){
            ElMessage.success("添加成功!");
            revert();
          }else{
            ElMessage.error(res&&res.msg||"重复的ip或道闸编号");
            revert();
          }
        })
      }
    }
  })
}
const revert =()=>{
  getAll();
  addDialog.value = false;
  formData.form={
    factory_id:null,
    cameraIp:"",
    port:"",
    monitorName:"",
    cameraName:"",
    deviceName:"",
    deviceType:"",
    status:null,
  }
}
const del = (row)=>{
  ElMessageBox.confirm("确定删除吗?").then(()=>{
    delCameraInfo(row).then(res=>{
      if(res.code==200){
        ElMessage.success("删除成功!");
        getAll();
      }else{
        ElMessage.error(res.msg);
      }
    })
  })
}
onMounted(() => {
  getAll();
  getFactorys();
});
onBeforeUnmount(()=>{
  // websocket.close();
})
</script>

<style scoped>
/* 面包屑字体颜色更改 */

.breadcrumbColor>>>.el-breadcrumb__inner {
  color: #000;
}
/* 内部header */

.inside-header {
  height: 20px;
  display: flex;
  justify-content: left;
  align-items: flex-start;
  background:#f2f4f5
}
/* 空心按钮样式 */

.empty-but {
  border: 1px solid #3780b9;
  color: #3780b9;
}
/* 实心按钮背景样式 */

.sele-but {
  background: #3780b9;
  border: 0px;
  border-radius: 2px;
  color: white;
}

.add-but {
  background: #dde5fe;
  color: #3780b9;
}
</style>
